import numpy as np
import pandas as pd
arr = np.random.randint(1,20,size=(3,3))
df = pd.DataFrame(arr,columns=['a','b','c'])
print('原始数据\n',df)
print('每列求聚合:\n',df.agg('sum'))
print('每列同时求和及平均值聚合:\n',df.agg(['sum','mean']))
def rang(arr):
    return arr.max() - arr.min()
print('各行分别求和，平均值和极差聚合:\n',df.agg({0:'sum',1:'mean',2:rang},axis=1))




pd.set_option('display.unicode.east_asian_width',True)
df = pd.DataFrame({'班级':['一班','一班','一班','二班','二班','二班',],
                   '姓名':['刘武','王振','赵胜','赵霞','方芳','齐婷',],
                   '语文':['85','102','96','126','130','135',],
                   '数学':['100','90','124','123','140','109',],
                   '英语':['83','110','123','103','135','90',]})
print('原始数据:\n',df)
group1 = df.groupby('班级')
print('以班级列按行分组')
for i in group1:
    print(i)
print('分组后一班的数据:\n',group1.get_group('一班'))
print('每个班每个科目的平均成绩：\n',group1.agg('mean',numeric_only=True))
group2 = df.groupby({'语文':'总成绩','数学':'总成绩','英语':'总成绩'},axis=1)
print('以列标签按列分组：')
for i in group2:
    print(i)
df['总成绩'] = group2.agg('sum')
print('添加总成绩后的数据')



pd.set_option('display.unicode.east_asian_width',True)
df = pd.DataFrame({'职业':['教师','司机','编辑'],
                   '城市':['北京','青岛','武汉']})
print('原始数据:\n',pd.get_dummies(df))
print('编码后的数据:\n',pd.get_dummies(df))
print('设置附加前缀指定列编码后的数据:\n',pd.get_dummies(df,prefix='居住地',prefix_sep='-',columns=['城市']))